package cn.steel.utils;

import cn.steel.service.MessageService;
import lombok.RequiredArgsConstructor;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

@Controller
@RequiredArgsConstructor
public class MessageWebSocketHandler {

    private final SimpMessagingTemplate messagingTemplate;
    private final MessageService messageService;

    @MessageMapping("/chat.sendMessage")
    public void sendMessage(@Payload MessagePayload payload) {
        // 保存消息到数据库
        messageService.sendMessage(payload.getSenderId(), payload.getReceiverId(), payload.getContent());

        // 广播消息给接收者
        messagingTemplate.convertAndSend(
                "/topic/messages/" + payload.getReceiverId(),
                payload
        );
    }
}

class MessagePayload {
    private Long senderId;
    private Long receiverId;
    private String content;

    // Getters and Setters
    public Long getSenderId() { return senderId; }
    public void setSenderId(Long senderId) { this.senderId = senderId; }
    public Long getReceiverId() { return receiverId; }
    public void setReceiverId(Long receiverId) { this.receiverId = receiverId; }
    public String getContent() { return content; }
    public void setContent(String content) { this.content = content; }
}